# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/10 19:21
@Auth ： 李天天
"""
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
def is_valid_measurements(points):
    """
    检查所有 Point 对象中所有字段的值是否都是 float 类型。
    如果有任一字段值不是 float，则返回 False。
    """
    for point in points:
        # 尝试获取内部字段字典，注意：_fields 为 InfluxDB Point 内部属性，具体实现可能会有所不同
        fields = getattr(point, '_fields', None)
        if fields is None:
            print("无法获取 Point 对象的字段信息，数据验证失败。")
            return False
        for value in fields.values():
            if not isinstance(value, float):
                return False
    return True

class InfluxDBHandler:
    def __init__(self, url=None, token=None, org=None, bucket=None):
        if not url:
            url = "http://10.10.118.92:8086"
        if not token:
            token = "z7TVAZCoJY6T9bA1adSArAbddRqjhVOpGL1OD-ihe1ErnU4mYCknalpS0mXUa6U_D_w3kpqLvoXZsZutboy7MQ=="
        if not org:
            org = "perf"
        if not bucket:
            bucket = "Zone_AI_new"
        self.client = InfluxDBClient(url=url, token=token, org=org)
        self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
        self.bucket = bucket

    def write_data(self, measurement, tags, fields):
        point = Point(measurement).tag(**tags).field(**fields)
        self.write_api.write(self.bucket, self.client.org, point)

    def write_mul_data(self, measurements):
        # 在写入前检查整组数据的合法性
        if not is_valid_measurements(measurements):
            print("数据包含非浮点数，整组数据抛弃，不进行写入。")
            return
        try:
            self.write_api.write(self.bucket, self.client.org, measurements)
            print("数据写入成功。")
        except Exception as e:
            print(f"写入数据时出错: {e}")

    def query_data(self, query):
        result = self.client.query_api().query(query, org=self.client.org)
        return list(result)

    def close_connection(self):
        self.client.close()
